<template>
  <div class="member-course-container">
    <h2>课程预约</h2>

    <!-- 会员信息 -->
    <el-card class="member-info-card" v-if="memberInfo.id">
      <template #header>
        <div class="card-header">
          <span>个人信息</span>
        </div>
      </template>
      <div class="member-info">
        <div class="info-item">
          <label>姓名：</label>
          <span>{{ memberInfo.name }}</span>
        </div>
        <div class="info-item">
          <label>手机号：</label>
          <span>{{ memberInfo.phone }}</span>
        </div>
        <div class="info-item">
          <label>邮箱：</label>
          <span>{{ memberInfo.email }}</span>
        </div>
      </div>
    </el-card>

    <!-- 课程列表 -->
    <el-card class="course-list-card">
      <template #header>
        <div class="card-header">
          <span>可预约课程</span>
          <el-button type="primary" @click="loadCourses">刷新</el-button>
        </div>
      </template>

      <el-table :data="courses" stripe>
        <el-table-column prop="name" label="课程名称" />
        <el-table-column prop="coach" label="教练" />
        <el-table-column prop="room" label="教室" />
        <el-table-column prop="startTime" label="上课时间" />
        <el-table-column prop="duration" label="时长(分钟)" />
        <el-table-column prop="bookedCount" label="已预约人数" />
        <el-table-column prop="maxCapacity" label="最大人数" />
        <el-table-column label="预约情况">
          <template #default="scope">
            <el-progress
                :percentage="calculateBookingPercentage(scope.row)"
                :status="getProgressStatus(scope.row)"
                :show-text="true"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
                type="primary"
                size="small"
                @click="reserveCourse(scope.row)"
                :disabled="isCourseFull(scope.row) || isAlreadyReserved(scope.row.id)">
              预约
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="coursePi.pageNo"
            v-model:page-size="coursePi.pageSize"
            :page-sizes="[10, 15, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="coursePi.total"
            @change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 我的预约 -->
    <el-card class="my-reservations-card">
      <template #header>
        <div class="card-header">
          <span>我的预约</span>
          <el-button type="primary" @click="loadReservations">刷新</el-button>
        </div>
      </template>

      <el-table :data="reservations" stripe>
        <el-table-column prop="course.name" label="课程名称" />
        <el-table-column prop="course.coach" label="教练" />
        <el-table-column prop="course.startTime" label="上课时间" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 0">待确认</el-tag>
            <el-tag type="success" v-else-if="scope.row.status === 1">已确认</el-tag>
            <el-tag type="danger" v-else>已取消</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
                size="small"
                @click="cancelReservation(scope.row)"
                :disabled="scope.row.status === 2">
              取消预约
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import api from '@/util/api'
import { ElMessage, ElMessageBox } from 'element-plus'

// 会员信息
const memberInfo = ref({})

// 课程数据
const courses = ref([])
const coursePi = ref({
  pageNo: 1,
  pageSize: 10,
  total: 0
})

// 预约数据
const reservations = ref([])

// 获取当前登录会员信息
async function loadMemberInfo() {
  try {
    const resp = await api({
      url: '/members/profile',
      method: 'get'
    })

    if (resp.success) {
      memberInfo.value = resp.data
    } else {
      ElMessage.error('获取个人信息失败: ' + (resp.msg || '未知错误'))
    }
  } catch (error) {
    ElMessage.error('获取个人信息失败: ' + error.message)
  }
}

// 加载课程列表
async function loadCourses(pageNo = 1, pageSize = 10) {
  try {
    const resp = await api({
      url: '/courses',
      method: 'get',
      params: {
        pageNo: pageNo,
        pageSize: pageSize
      }
    })

    if (resp.success) {
      courses.value = resp.data.records
      coursePi.value.pageNo = resp.data.current
      coursePi.value.pageSize = resp.data.size
      coursePi.value.total = resp.data.total
    } else {
      ElMessage.error('获取课程列表失败: ' + (resp.msg || '未知错误'))
    }
  } catch (error) {
    ElMessage.error('获取课程列表失败: ' + error.message)
  }
}

// 加载我的预约
async function loadReservations() {
  try {
    const resp = await api({
      url: '/reservations/my',
      method: 'get'
    })

    if (resp.success) {
      reservations.value = resp.data
    } else {
      ElMessage.error('获取预约信息失败: ' + (resp.msg || '未知错误'))
    }
  } catch (error) {
    ElMessage.error('获取预约信息失败: ' + error.message)
  }
}

// 预约课程
async function reserveCourse(course) {
  ElMessageBox.confirm(`确定要预约课程 "${course.name}" 吗？`, '预约确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 首先确保我们有会员信息
      if (!memberInfo.value.id) {
        await loadMemberInfo()
        if (!memberInfo.value.id) {
          ElMessage.error('无法获取会员信息，预约失败')
          return
        }
      }

      const resp = await api({
        url: '/reservations/reserve',
        method: 'post',
        data: {
          memberId: memberInfo.value.id,
          courseId: course.id,
          courseType: 0, // 团课
          status: 1 // 确认
        }
      })

      if (resp.success) {
        ElMessage.success('预约成功')
        loadCourses()
        loadReservations()
      } else {
        ElMessage.error(resp.msg || '预约失败')
      }
    } catch (error) {
      ElMessage.error('预约失败: ' + error.message)
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 取消预约
async function cancelReservation(reservation) {
  ElMessageBox.confirm('确定要取消预约吗？', '取消预约', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const resp = await api({
        url: `/reservations/cancel/${reservation.id}`,
        method: 'delete'
      })

      if (resp.success) {
        ElMessage.success('取消预约成功')
        loadCourses()
        loadReservations()
      } else {
        ElMessage.error(resp.msg || '取消预约失败')
      }
    } catch (error) {
      ElMessage.error('取消预约失败: ' + error.message)
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 检查课程是否已满
function isCourseFull(course) {
  return course.bookedCount >= course.maxCapacity
}

// 检查是否已经预约了该课程
function isAlreadyReserved(courseId) {
  return reservations.value.some(reservation =>
      reservation.course.id === courseId && reservation.status !== 2)
}

// 计算预约百分比
function calculateBookingPercentage(course) {
  if (!course.maxCapacity || course.maxCapacity <= 0) {
    return 0
  }
  return Math.round((course.bookedCount / course.maxCapacity) * 100)
}

// 获取进度条状态
function getProgressStatus(course) {
  const percentage = calculateBookingPercentage(course)
  if (percentage >= 90) {
    return 'exception' // 红色
  } else if (percentage >= 70) {
    return 'warning' // 黄色
  } else {
    return undefined // 蓝色
  }
}

// 处理分页变化
function handlePageChange(pageNo, pageSize) {
  loadCourses(pageNo, pageSize)
}

// 初始化加载
onMounted(() => {
  loadMemberInfo()
  loadCourses()
  loadReservations()
})
</script>

<style scoped>
.member-course-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.member-info-card {
  margin-bottom: 20px;
}

.member-info {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 15px;
}

.info-item {
  display: flex;
  align-items: center;
}

.info-item label {
  font-weight: bold;
  margin-right: 10px;
  min-width: 60px;
}

.course-list-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
